<?php

namespace app\admin\model;

use think\Model;

use think\Db;
use think\Request;
use think\Exception;//事务处理

class Admin extends Model
{
    //获取所有用户相关数据
    public function getadmin($res)
    {
        $map = array();
        $admin = session('admin');
        //不是管理员只能看自己部门下的员工
        if ($admin['position_id'] != 1 && $admin['position_id'] != 2) {
            //获取这个部门下的所有部门id
            $fid = array_column(getFrames('department', null, $res['country_id']), 'id');
            $fidmap = implode(',', $fid);
            $map['a.department_id'] = array('in', $fidmap);
        }
        //状态查询 1在职 2 离职 3锁定(搜索所有的状态)
        if ($res['status'] != 11) {
            if (isset($res['status']) && $res['status']) {
                $map['a.status'] = $res['status'];
            }
        }
        //部门查询
        if (isset($res['department_id']) && $res['department_id']) {
            $map['a.department_id'] = $res['department_id'];
        }
        //职位查询
        if (isset($res['position_id']) && $res['position_id']) {
            $map['a.position_id'] = $res['position_id'];
        }
        //账号，昵称 姓名查询
        if (isset($res['dname']) && $res['dname']) {
            $maps['a.name'] = array('like', '%' . removeBlank($res['dname']) . '%');//账号
            $maps['a.nickname'] = array('like', '%' . removeBlank($res['dname']) . '%');//昵称
            $maps['b.lastname'] = array('like', '%' . removeBlank($res['dname']) . '%');//姓
            $maps['b.firstname'] = array('like', '%' . removeBlank($res['dname']) . '%');//名
        } else {
            $maps = array();
        }
        $datares = $this->alias('a')->join('nt_admin_info b', 'a.id=b.admin_id', 'left')->where(function ($query) use ($map) {
            $query->where($map);
        })->where(function ($query) use ($maps) {
            $query->whereOr($maps);
        })->field('a.*,b.firstname,b.lastname,b.birthday,b.remarks,b.sex,b.marry,b.wage,b.education')->order('a.create_at')->page($res['page'], $res['pageSize'])->select();
        $langs = $res['lang'];
        foreach ($datares as $datareskey => $datareval) {
            //更新时间
            $datares[$datareskey]['update_date'] = getTimeDate($datareval['update_at'], 12);
            if ($langs != 'zh') {
                //登录时间
                if ($datareval['login_time']) {
                    $datares[$datareskey]['login_date'] = getTimeDate($datareval['login_time'], 9);
                } else {
                    $datares[$datareskey]['login_date'] = '-';
                }
                $datares[$datareskey]['create_date'] = getTimeDate($datareval['create_at'], 9);
                //入职时间
                $datares[$datareskey]['work_day_date'] = getTimeDate($datareval['work_day'], 8);
                $datares[$datareskey]['username'] = $datareval['lastname'] . ' ' . $datareval['firstname'];//名姓
            } else {
                if ($datareval['login_time']) {
                    //登录时间
                    $datares[$datareskey]['login_date'] = getTimeDate($datareval['login_time'], 12);
                } else {
                    $datares[$datareskey]['login_date'] = '-';
                }
                //入职时间
                $datares[$datareskey]['work_day_date'] = getTimeDate($datareval['work_day'], 7);
                $datares[$datareskey]['create_date'] = getTimeDate($datareval['create_at'], 12);
                $datares[$datareskey]['username'] = $datareval['firstname'] . ' ' . $datareval['lastname'];//姓名
            }
            //管理员可以编辑所有人的
            if ($admin['id'] == $datareval['id'] || $admin['position_id'] == 1) {
                $datares[$datareskey]['isedit'] = 1;
            } else {
                $datares[$datareskey]['isedit'] = 0;
            }
            //职位名称
            $rolewhere['mkey'] = 'position_' . $datareval['position_id'];
            $datares[$datareskey]['positionname'] = getlangname('multi_lang', $rolewhere, $langs);
            //部门名称
            $framewhere['mkey'] = 'department_' . $datareval['department_id'];
            $datares[$datareskey]['departmentname'] = getlangname('multi_lang', $framewhere, $langs);

            $datares[$datareskey]['sex'] = $this->getmanagelang($datareval['sex'], 1);//性别
            //登陆者的默认语言
            $datares[$datareskey]['langperson'] = $this->getmanagelang($datareval['language_id'], 2);//语言
            $datares[$datareskey]['mangname'] = getinfo($datareval['update_id'], 'admin')['nickname'];//编辑者
            $datares[$datareskey]['age'] = getTimeDate(null, 1) - getTimeDate($datareval['birthday'], 1); //年龄
        }
        $data['data'] = $datares;
        $data['ids'] = array_column($datares, 'id');
        $data['count'] = $this->alias('a')->join('nt_admin_info b', 'a.id=b.admin_id', 'left')->where(function ($query) use ($map) {
            $query->where($map);
        })->where(function ($query) use ($maps) {
            $query->whereOr($maps);
        })->count();
        return $data;
    }

    //获取对应用户的详情数据
    public function getxiangqin($res)
    {
        $langs = $res['lang'];//语言标志
        $infodata = $this->alias('a')->join('nt_admin_info b', 'a.id=b.admin_id', 'left')->field('a.*,b.firstname,b.lastname,b.birthday,b.remarks,b.sex,b.marry,b.wage,b.education')->where('a.id', $res['id'])->find();
        //部门名称
        $framewhere['mkey'] = 'department_' . $infodata['department_id'];
        $infodata['departmentname'] = getlangname('multi_lang', $framewhere, $langs);

        //职位名称
        $rolewhere['mkey'] = 'position_' . $infodata['position_id'];
        $infodata['positionname'] = getlangname('multi_lang', $rolewhere, $langs);

        $infodata['update_at'] = getTimeDate($infodata['update_at'], 12);//更新时间
        if ($res['lang'] != 'zh') {
            $infodata['work_day_date'] = getTimeDate($infodata['work_day'], 8);
            $infodata['birthday_date'] = getTimeDate($infodata['birthday'], 8);
            $infodata['login_time'] = getTimeDate($infodata['login_time'], 9);//登陆时间
            $infodata['username'] = $infodata['lastname'] . ' ' . $infodata['firstname'];//名姓
            if ($infodata['leave_day']) {
                //离职日期
                $infodata['leave_day_date'] = getTimeDate($infodata['leave_day'], 8);
            }
        } else {
            $infodata['work_day_date'] = getTimeDate($infodata['work_day'], 7);//入职时间
            $infodata['birthday_date'] = getTimeDate($infodata['birthday'], 7);//出生年月
            $infodata['username'] = $infodata['firstname'] . ' ' . $infodata['lastname'];//姓名
            $infodata['login_time'] = getTimeDate($infodata['login_time'], 12);//登陆时间
            if ($infodata['leave_day']) {
                $infodata['leave_day_date'] = getTimeDate($infodata['leave_day'], 7);
            }
        }
        $infodata['mangname'] = getinfo($infodata['update_id'], 'admin')['nickname'];//编辑者
        $infodata['sex'] = $this->getmanagelang($infodata['sex'], 1);//性别
        $infodata['langperson'] = $this->getmanagelang($infodata['language_id'], 2);//语言
        $infodata['status'] = $this->getmanagelang($infodata['status'], 3);//状态
        $infodata['marry'] = $this->getmanagelang($infodata['marry'], 4);//婚姻状态
        $infodata['education'] = $this->getmanagelang($infodata['education'], 5);//学历
        return $infodata;
    }

    //个人资料的查看(头部)
    public function getadminper()
    {
        $lang = is_lang();
        //获取个人的相关信息
        $uidname = session('admin');
        $uidname['langdata'] = getlangnames();//语言
        $rolewhere['mkey'] = 'position_' . $uidname['position_id'];
        $uidname['posnames'] = getlangname('multi_lang', $rolewhere, $lang);//职务名称

        $framewhere['mkey'] = 'department_' . $uidname['department_id'];
        $uidname['framnames'] = getlangname('multi_lang', $framewhere, $lang);//部门名称

        if ($lang != 'zh') {
            $uidname['birthday_date'] = getTimeDate($uidname['birthday'], 8);//出生年月
            $uidname['login_time'] = getTimeDate($uidname['login_time'], 9);//登陆时间
            $uidname['username'] = $uidname['lastname'] . ' ' . $uidname['firstname'];//名姓
        } else {
            $uidname['birthday_date'] = getTimeDate($uidname['birthday'], 7);//出生年月
            $uidname['login_time'] = getTimeDate($uidname['login_time'], 12);//登陆时间
            $uidname['username'] = $uidname['firstname'] . ' ' . $uidname['lastname'];//姓名
        }
        $uidname['loginipaddress'] = $uidname['loginaddress'];//登录地址
        $uidname['sex'] = $this->getmanagelang($uidname['sex'], 1);//性别
        $uidname['marry'] = $this->getmanagelang($uidname['marry'], 4);//婚姻状态
        $uidname['education'] = $this->getmanagelang($uidname['education'], 5);//学历
        return $uidname;
    }

    //头部个人资料提交
    public function means($data)
    {
        $adminid = $this->where('id', session('userid'))->setField('language_id', $data['language_id']);
        if ($adminid !== false) {
            return array('msg' => $data['nickname'] . lang("change_successful"), 'status' => 1);
        } else {
            return array('msg' => $data['nickname'] . lang("change_failed"), 'status' => 0);
        }
    }

    //处理语言标志的显示
    protected function getmanagelang($id, $code)
    {
        switch ($id) {
            case '1':
                //通过语言id去获取对应的语言的数据
                $sex = lang("man");//男
                $status = lang("on_the_job");//状态
                $bachelordom = lang("married");//婚姻
                $education = lang("below_high_school");//学历
                break;
            case '2':
                $sex = lang("woman");//女
                $status = lang("departure");//状态
                $bachelordom = lang("unmarried");//婚姻
                $education = lang("technical_secondary_school");//学历
                break;
            case '3':
                $status = lang("locking");//状态
                $sex = $bachelordom = '';
                $education = lang("college_degree");//学历
                break;
            case '4':
                $bachelordom = $status = $sex = '';
                $education = lang("undergraduate");//学历
                break;
            case '5':
                $bachelordom = $status = $sex = '';
                $education = lang("Master_degree");//学历
                break;
            case '6':
                $bachelordom = $status = $sex = '';
                $education = lang("Doctor");//学历
                break;
            case '7':
                $bachelordom = $status = $sex = '';
                $education = lang("unknown");//学历
                break;
            default:
                $education = $bachelordom = $status = $sex = '';
                break;
        }
        if ($code == 1) {
            return $sex;
        } elseif ($code == 2) {
            $idname = getinfo($id, 'language', 'name')['name'];
            $mkey = Db::name('dict')->field('abbreviation')->where('content', $idname)->find();
            $lang = $mkey ? lang($mkey['abbreviation']) : $idname;
            return $lang;
        } elseif ($code == 3) {
            return $status;
        } elseif ($code == 4) {
            return $bachelordom;
        } elseif ($code == 5) {
            return $education;
        }
    }

    //用户的添加与编辑的接口统计
    public function addeditadmin($data)
    {
        $ckdata = notEmpty(['name' => lang("account"), 'language_id' => lang("language"), 'nickname' => lang("nickname"), 'position_id' => lang("job"), 'work_day' => lang("entry_time"), 'wage' => lang("basic_salary"), 'birthday' => lang("brithday"), 'department_id' => lang("department")]);
        if ($ckdata['status'] == 2) {
            return $ckdata;
        }
        $name = trim($data['name']);
        if (!$data['firstname'] || !$data['lastname']) {
            return array('msg' => lang("name_can't_be_empty"), 'status' => 2);
        }
        //账号
        if (!pregUser($name, 1, 20)) {
            return array('msg' => lang("account_format_error"), 'status' => 0);
        }
        //设置个人的权限
        if ($data['position_id']) {
            $data['auth_ids'] = Db::name('position')->where('id', $data['position_id'])->value('auth_ids');
        }
        $langcode = getValue('language', ['id' => $data['language_id']], 'code');
        $firstname = trim($data['firstname']);
        $lastname = trim($data['lastname']);
        $data['work_day'] = strtotime($data['work_day']);//入职时间
        $data['birthday'] = strtotime($data['birthday']);//出生年月
        unset($data['lang']);
        //判断编辑或者添加
        if ($data['act'] == 'personneladd') {
            //查看账号是否被占用
            $infoma = $this->where(array('name' => $name))->find();
            if ($infoma) {
                return array('msg' => $name . lang("account_exists"), 'status' => 3);
            }
            //现在对用户填入的数据进行入库的操作
            unset($data['id']);
            $data['create_at'] = $data['update_at'] = time();
            $data['create_id'] = $data['update_id'] = session('userid');
            $dpass = generatePassword();//随机密码
            $passsalt = encrypt_password($dpass);
            $data['passwd'] = $passsalt['password'];//密文
            $data['salt'] = $passsalt['salt'];//盐
            Db::startTrans();
            $adminid = $this->strict(false)->insertGetId($data);
            //送货员工的写入
            if (in_array($data['position_id'], ['31', '37', '38', '39'])) {
                $insertman['admin_id'] = $adminid;
                $insertman['work_day'] = time();
                //货车司机、送货队长、送货员、实习送货员
                Db::name('deliveryman')->insert($insertman);//表示该员工是送货员工
            }
            $data['admin_id'] = $adminid;
            //设置用户联系方式
            if (isset($data['linkarr'])) {
                $datamethod['linkman_id'] = $adminid;//用户id
                $datamethod['linkmethods'] = $data['linkarr'];//联系方式
                $linkmethid = model('linkman')->addlinkmeth($datamethod, 2);
                if ($linkmethid['status'] == 0) {
                    return array('msg' => $linkmethid['msg'], 'status' => 0);
                    exit;
                }
            }
            $admininfoid = Db::name('admin_info')->strict(false)->insertGetId($data);
            if ($adminid && $admininfoid) {
                Db::commit();
                return array('status' => 1, 'msg' => '员工(' . $name . ')' . lang("added_successfully") . ': ' . lang('account') . '：' . $data['name'] . ',' . lang('password') . '：' . $dpass);
            } else {
                return array('status' => 0, 'msg' => $name . lang("add_failed"));
            }
        } elseif ($data['act'] == 'personneledit') {
            if ($data['leave_day']) {
                $data['leave_day'] = strtotime($data['leave_day']);//离职时间
            } else {
                $data['leave_day'] = null;
            }
            $map['id'] = $data['id'];
            //判断状态
            $infostatus = $this->where($map)->find();
            if ($infostatus['status'] == 3) {
                return array('msg' => $name . lang("is_locked_and_can't_be_edited"), 'status' => 0);
            }
            Db::name('adminattr_value')->where('admin_id', $data['id'])->delete();
            if (isset($data['linkarr'])) {
                $datamethod['linkman_id'] = $data['id'];//用户id
                $datamethod['linkmethods'] = $data['linkarr'];//联系方式
                $linkmethid = model('linkman')->addlinkmeth($datamethod, 2);
                if ($linkmethid['status'] == 0) {
                    return array('msg' => $linkmethid['msg'], 'status' => 0);
                    exit;
                }
            }
            $deliverinfo = Db::name('deliveryman')->where('admin_id', $infostatus['id'])->find();
            //职位发生改变时，权限就是新职位的权限
            if ($data['position_id'] != $infostatus['position_id']) {
                //货车司机、送货队长、送货员、实习送货员
                if (in_array($data['position_id'], ['31', '37', '38', '39'])) {
                    //改变的职位刚好是送货的职位
                    if (!$deliverinfo) {
                        //重新添加该送货员工
                        $insertman['admin_id'] = $infostatus['id'];
                        $insertman['work_day'] = time();
                        Db::name('deliveryman')->insert($insertman);//表示该员工是送货员工
                    }
                } else {
                    //改变的职位不是送货职位
                    if ($deliverinfo) {
                        //送货人员
                        Db::name('deliveryman')->where('admin_id', $infostatus['id'])->delete();
                        //送货人员月记录表
                        Db::name('deliveryman_month')->where('admin_id', $infostatus['id'])->delete();
                    }
                }
                $data['auth_ids'] = Db::name('position')->where('id', $data['position_id'])->value('auth_ids');
            } else {
                //权限就用原来的
                $data['auth_ids'] = $infostatus['auth_ids'];
                //判断这个送货职位是否存在
                if (in_array($data['position_id'], ['31', '37', '38', '39'])) {
                    $deinfo = Db::name('deliveryman')->where('admin_id', $data['id'])->find();
                    if (!$deinfo) {
                        $insertmasn['admin_id'] = $data['id'];
                        $insertmasn['work_day'] = time();
                        Db::name('deliveryman')->insert($insertmasn);
                    }
                }
            }
            //对数据进行编辑
            $adminupdate = array(
                'name' => $name,
                'nickname' => trim($data['nickname']),
                'department_id' => $data['department_id'],
                'position_id' => $data['position_id'],
                'language_id' => $data['language_id'],
                'update_id' => session('userid'),
                'update_at' => time(),
                'status' => $data['status'],
                'work_day' => $data['work_day'],
                'auth_ids' => $data['auth_ids'],
                'leave_day' => $data['leave_day'],
            );
            $admininfoupdate = array(
                'firstname' => trim($data['firstname']),
                'lastname' => trim($data['lastname']),
                'birthday' => $data['birthday'],
                'sex' => $data['sex'],
                'marry' => $data['marry'],
                'wage' => $data['wage'],
                'education' => $data['education'],
            );
            Db::startTrans();
            $resupadminid = $this->where($map)->update($adminupdate);
            $resadmininfoid = Db::name('admin_info')->where('admin_id', $data['id'])->update($admininfoupdate);
            if ($resupadminid !== false && $resadmininfoid !== false) {
                Db::commit();
                return array('status' => 1, 'msg' => $name . lang("edited_successfully"));
            } else {
                return array('status' => 0, 'msg' => $name . lang("edit_failed"));
            }
        }
    }

    //设置权限
    public function setroot($data)
    {
        if (!isset($data['auth_ids'])) {
            return array('msg' => lang("personal_permission_can't_be_empty"), 'status' => 2);
        }
        $auth_ids = $data['auth_ids'];
        //通过里面的id，判断最顶级的id是否写入
        $menupid = Db::name('menu')->where(['pid' => 0, 'disable' => 0])->select();
        foreach ($menupid as $menupidkey => $menupidval) {
            //获取顶级下的二级
            $idarr = array_column(Db::name('menu')->where(['pid' => $menupidval['id'], 'disable' => 0])->select(), 'id');
            //获取两个数组的交集
            $arrempty = array_intersect($idarr, $auth_ids);
            if (!empty($arrempty)) {
                array_push($auth_ids, $menupidval['id']);
            }
        }
        //问题反馈
        $arrfeedback = array('50', '404', '405');
        $auth_ids = implode(',', array_unique(array_merge($auth_ids, $arrfeedback)));
        $authids = $this->where('id', $data['id'])->setField('auth_ids', $auth_ids);
        if ($authids !== false) {
            return array('msg' => $data['nickname'] . lang("setting_permission_successfully"), 'status' => 1);
        } else {
            return array('msg' => $data['nickname'] . lang("failed_setting_permission"), 'status' => 0);
        }

    }

    //检测登录的时的判断
    public function getLoginStatu($data)
    {
        //file_put_contents("test.txt","传入数据111 = ".json_encode($data)."\r\n", FILE_APPEND);
        $verify = '';
        if (!$data['name']) {
            return array('msg' => lang("account_can't_be_empty"), 'status' => 2);
        }
        if (!$data['passwd']) {
            return array('msg' => lang("password_can't_be_empty"), 'status' => 2);
        }
        if (!$data['name'] || !$data['passwd']) {
            return array('msg' => lang("account_and_password_can't_be_empty"), 'status' => 2);
        }
        //对所提交的数据进行验证
        if (cookie('admin_cache') >= 3 && isset($data['verify'])) {
            if (!$data['verify']) {
                return array('status' => 2, 'msg' => lang('verification_code') . lang("can't_be_empty"));
            }
            if (!captcha_check($data['verify'])) {
                return array('status' => 0, 'msg' => lang("wrong_verification_code"));
            }
            $verify = $data['verify'];
        }
        $info = $this->where(['name' => $data['name']])->find();
        if ($info['status'] == 3) {
            //判断是否锁定
            return array('msg' => lang("the_user_is_locked,_please_contact_the_administrator"), 'status' => 0);
            exit();
        }
        $password = encrypt_password($data['passwd'], $info['salt'])['password'];//加密的密文
        $login = $this->where(['name' => $data['name'], 'passwd' => $password])->find();
        if (!$login) {
            //增加验证码的错误次数
            $this->getcode(1);
            //如果用户输入了验证码并且账号密码错误,增加锁定次数
            if ($verify) {
                $this->getcode(2);
                if (cookie('admin_lock') >= 3) {
                    //表示有验证码的输入依然错误3次，账号正确，密码错误，验证码正确,锁定用户
                    $this->where(['name' => $data['name']])->setField('status', 3);
                }
            }
            return array('msg' => lang("account_or_password_incorrect"), 'status' => 0, 'count' => cookie('admin_cache'));
        } else {
            //更新这个用户的语言
            $lang = getinfo($login['language_id'], 'language', 'code');
            is_lang($lang['code']);
            $ip = getIp();//登录的ip
            $resdata['loginip'] = $ip;
            $url = 'https://www.toolnb.com/Tools/Api/IP.html';
            $ardress = curlRequest($url, null)['data'];
            if ($ardress) {
                if ($ardress['country']) {
                    $address = $ardress['country'] . '/' . $ardress['cz_country'];
                } else {
                    $address = $ardress['cz_country'];
                }
                $resdata['loginaddress'] = $address;
            } else {
                $resdata['loginaddress'] = '';
            }
            $resdata['login_time'] = time();//登录时间
            //反馈问题id，都是有的
            $auth_idsarr = explode(',', $login['auth_ids']);
            $arrfeedback = array('50', '404', '405');
            $resdata['auth_ids'] = implode(',', array_unique(array_merge($auth_idsarr, $arrfeedback)));
            $this->where(['name' => $data['name'], 'passwd' => $password])->update($resdata);//更新登录后的信息
            session('userid', $login['id']);//当前用户的did
            cookie('admin_cache', null);
            cookie('admin_lock', null);
            //这里主要是用在同一个账号多个用户登录
//                $redis = new \Redis();
//                $redis->connect('127.0.0.1',6379);
//                $redis->auth("huxing");
//                $session_id = session_id();
//                $redis->set("userid".$login['id'],$session_id);
//                $redis->set("logintime".$login['id'],time());
            return array('msg' => lang("login_successful"), 'status' => 1);
        }
    }

//处理验证码的相关的操作
    private function getcode($code)
    {
        if ($code == 1) {
            $admincode = cookie('admin_cache');
            if (!$admincode) {
                cookie('admin_cache', 1);
            } else {
                cookie('admin_cache', cookie('admin_cache') + 1);
            }
        } else {
            $adminlock = cookie('admin_lock');
            //锁定时间设置一小时
            if (!$adminlock) {
                cookie('admin_lock', 1);
            } else {
                cookie('admin_lock', cookie('admin_lock') + 1);
            }
        }
    }

    //修改密码
    public function editpass($data)
    {
        $ckdata = notEmpty(['oldpass' => lang("current_password"), 'newpass' => lang("new_password"), 'confirm' => lang("confirm_password")]);
        if ($ckdata['status'] == 2) {
            return $ckdata;
        }
        //验证两次密码
        if ($data['newpass'] != $data['confirm']) {
            return array('msg' => lang("the_new_password_doesn't_match_the_cofirm_passward"), 'status' => 0);
        }
        //验证密码
        if (!pregPW($data['newpass'], 1, 20)) {
            return array('msg' => lang("password_format_doesn't_match"), 'status' => 0);
        }
        $uid = session('userid');
        $info = getinfo($uid, 'admin');
        //验证旧密码是否错误
        $oldpass = encrypt_password($data['oldpass'], $info['salt'])['password'];//旧
        $newpass = encrypt_password($data['newpass']);//新
        if (!$info) {
            return array('msg' => lang("server_error"), 'status' => 0);
        } else {
            if ($info['passwd'] != $oldpass) {
                return array('msg' => lang("the_current_password_is_wrong,_please_fill_in_again"), 'status' => 0);
            } else {
                //对用户的密码进行修改，并退出网站
                $updata['passwd'] = $newpass['password'];
                $updata['salt'] = $newpass['salt'];
                $updata['update_at'] = time();
                $res = $this->where('id', $uid)->update($updata);
                if (!$res) {
                    return array('status' => 0, 'msg' => lang("edit_failed"));
                } else {
                    return array('status' => 1, 'msg' => lang("edited_successfully"));
                }
            }
        }

    }

    //重置密码
    public function resetadmin($data)
    {
        $map['id'] = $data['id'];
        $dpass = generatePassword();//随机密码
        $passsalt = encrypt_password($dpass);
        $update['passwd'] = $passsalt['password'];//密文
        $update['salt'] = $passsalt['salt'];//盐
        $this->where($map)->update($update);//更新数据库的密码
        $retdata['pass'] = $dpass;
        $retdata['dname'] = $data['dname'];
        return $retdata;
    }

    //处理用户锁定 离职 复职
    public function lockleaveresume($data)
    {
        $ids = $data['id'];
        if ($ids) {
            //单独获取这个查询数据的状态
            $deldata = $this->field('status,create_at,nickname,leave_day')->where("id in($ids)")->select();
            $arrstatus = array_column($deldata, 'status');//状态
            $arrnickname = array_column($deldata, 'nickname');//昵称
            if (count($arrnickname) > 3) {
                $namenick = $arrnickname[0] . $arrnickname[1] . $arrnickname[2] . '...';
            } else {
                $namenick = implode(",", $arrnickname);
            }
        }
        if ($data['act'] == 'lock') {
            if (!$ids) {
                return array('msg' => lang("please,_select_a_user_to_lock"), 'status' => 3);
            } else {
                $update['status'] = 3;//锁定
                $ret = $this->where("id in($ids)")->update($update);
                $success = $namenick . lang("locked_successfully");
                $failed = $namenick . lang("lock_failed");
            }
        } elseif ($data['act'] == 'leave') {
            if (!$ids) {
                return array('msg' => lang("please,_select_a_user_to_resignation"), 'status' => 3);
            } else {
                if (in_array('3', $arrstatus)) {
                    return array('msg' => $namenick . lang("status_is_locked_and_can't_be_resign"), 'status' => 0);
                    exit;
                }
                $update['status'] = 2;//离职
                $update['leave_day'] = time();//离职时间
                $ret = $this->where("id in($ids)")->update($update);
                $success = $namenick . lang("resignation_successfully");
                $failed = $namenick . lang("failed_resignation");
            }
        } elseif ($data['act'] == 'resume') {
            //复职
            if (!$ids) {
                return array('msg' => lang("please,_select_a_user_to_reinstate"), 'status' => 3);
            } else {
                if (in_array('3', $arrstatus)) {
                    return array('msg' => $namenick . lang("status_is_locked_and_can't_be_reinstate"), 'status' => 0);
                    exit;
                }
                $update['status'] = 1;//在职
                $update['leave_day'] = null;//离职时间
                $ret = $this->where("id in($ids)")->update($update);
                $success = $namenick . lang("reinstatement_successful");
                $failed = $namenick . lang("reinstatement_failure");
            }
        } elseif ($data['act'] == 'delete') {
            if (!$ids) {
                return array('msg' => lang("please_select_user_to_clear"), 'status' => 3);
            } else {
                $posarrids = array_column($this->field('position_id')->where("id in($ids)")->select(), 'position_id');//删除的职位id
                if (in_array(1, $posarrids)) {
                    return array('msg' => lang("administrator_can't_clear"), 'status' => 0);
                    exit;
                } else {
                    if (in_array('3', $arrstatus)) {
                        return array('msg' => $namenick . lang("status_is_locked_and_can't_be_cleared"), 'status' => 0);
                        exit;
                    }
                    if (in_array('1', $arrstatus)) {
                        return array('msg' => $namenick . '在职状态无法清除', 'status' => 0);
                        exit;
                    }
                    foreach ($deldata as $arrtimekey => $arrtimeval) {
                        if (!$arrtimeval['leave_day'] || $arrtimeval['leave_day'] == 0) {
                            return array('msg' => '没有离职时间，无法清除', 'status' => 0);
                            exit;
                        }
                        $leavetime = getTimeDate($arrtimeval['leave_day'], 7);//离职时间
                        //清除时间撮
                        $deltime = strtotime("5year", $arrtimeval['leave_day']);
                        //最后删除时间
                        $failtime = date("Y-m-d", $deltime);
                        if ($deltime > time()) {
                            return array('msg' => $namenick . '于' . $leavetime . '离职，他的档案要在' . $failtime . '后才可以清除', 'status' => 0);
                            exit;
                        }
                    }
                    $ret = $this->where("id in($ids)")->delete();
                    Db::name('admin_info')->where("admin_id in($ids)")->delete();
                    //送货员工表
                    Db::name('deliveryman')->where("admin_id in($ids)")->delete();
                    //送货员工-月记录表
                    Db::name('deliveryman_month')->where("admin_id in($ids)")->delete();
                    $success = $namenick . lang("cleared_successfully");
                    $failed = $namenick . lang("clear_failed");
                }
            }
        } elseif ($data['act'] == 'unlock') {
            if (!$ids) {
                return array('msg' => lang("please_select_the_user_to_unlock"), 'status' => 3);
            } else {
                $update['status'] = 1;//解锁
                $ret = $this->where("id in($ids)")->update($update);
                $success = $namenick . lang("unlock_successful_");
                $failed = $namenick . lang("unlock_failed");
            }
        }
        if ($ret === false) {
            return array('status' => 0, 'msg' => $failed);
        } else {
            return array('status' => 1, 'msg' => $success);
        }
    }

    //处理用户的反馈问题
    public function feedback($data)
    {
        $admin = session('admin');
        $ckdata = notEmpty(['menu_id' => '问题模块', 'content' => '反馈内容']);
        if ($ckdata['status'] == 2) {
            return $ckdata;
        }
        $urldata = explode('?', $_SERVER['HTTP_REFERER']);
        $data['url'] = $urldata[0];
        if (isset($urldata[1])) {
            $data['param'] = $urldata[1];
        }
        $data['position_id'] = $admin['position_id'];
        $data['admin_id'] = $data['create_id'] = $admin['id'];
        $data['create_at'] = time();
        $res = Db::name('feedback')->strict(false)->insert($data);
        if ($res) {
            return array('status' => 1, 'msg' => '反馈成功');
        } else {
            return array('status' => 0, 'msg' => '反馈失败');
        }

    }
}


